package com.du.interceptors;

import static com.du.constants.SsmConstans.*;
import com.du.constants.SsmConstans;
import com.du.domain.User;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 拦截器链:登录认证拦截器
 */
@Component
public class AuthorityInterceptor implements HandlerInterceptor {

    @Override
//    拦截器前处理(return flase：拦截)
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //通过request获取Session
        HttpSession session = request.getSession();
        //通过Session拿到Session域中保存的用户信息
        User user = (User) session.getAttribute(USER_INFO);
        //校验
        if (user==null){
            //用户未登录,重定向到登录页面
            response.sendRedirect(request.getContextPath()+"/user/login-ui");
            return false;
        }
        else {
            //用户已登录，放行
            return true;

        }
    }

    @Override
    //拦截器后处理
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//        System.out.println("拦截器后处理");
    }

    @Override
    //拦截器最终处理
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        System.out.println("拦截器最终处理");

    }
}
